/* 我们发现每个物料组件都要使用useDrop改造成可drop(放置)的，那么随着物料组件增多要重复写好多代码
    所以我们考虑对公共逻辑进行抽离
 */
import { useDrop } from "react-dnd";
import { useComponentsStore, getComponentById } from "../stores/components";
import { useComponentConfigStore } from "../stores/component-config";

export interface ItemType {
    type: string
    dragType?: 'move'|'add'
    id?: number
}

export function useMaterialDrop(accept: string[], id: number) {
    const { addComponent, deleteComponent, components } = useComponentsStore();
    const { componentConfig } = useComponentConfigStore();

    const [{canDrop}, drop] = useDrop(()=>({
        accept,
        drop(item: ItemType, monitor) {
            if(monitor.didDrop()) return;
            if(item.dragType === 'move') {
                const component = getComponentById(item.id!, components)!;
                deleteComponent(item.id!);
                addComponent(component, id);
            }else {
                const config = componentConfig[item.type];
                addComponent({
                    id: new Date().getTime(),
                    name: item.type,
                    props: item.type === 'FormItem' ? {...config.defaultProps, name: Math.random().toString().slice(2, 8)} : config.defaultProps,
                    desc: config.desc
                }, id);
            }
        },
        collect: (monitor)=>({
            canDrop: monitor.canDrop()
        })
    }))

    return { canDrop, drop }
}